
import { Component } from '@angular/core';
import { NzMessageService } from 'ng-zorro-antd/message';
import { Item1Component } from '../item1/item1.component';
import { Item2Component } from '../item2/item2.component';
import { Item3Component } from '../item3/item3.component';

interface MenuItem {
  id: number;
  name: string;
  icon?: string;
  component?: any;
  children?: MenuItem[];
  expanded?: boolean;
  active?: boolean;
}

interface Module {
  id: number;
  name: string;
  icon: string;
  component?: any;
  menuItems: MenuItem[];
}

interface Tab {
  title: string;
  component: any;
  active: boolean;
  moduleId: number;
  menuItemId: number;
}

@Component({
  selector: 'app-main',
  templateUrl: './main.component.html',
  styleUrls: ['./main.component.scss']
})
export class MainComponent {
  modules: Module[] = [
    {
      id: 1,
      name: 'Module 1',
      icon: 'appstore',
      menuItems: [
        {
          id: 1,
          name: 'Parent 1',
          icon: 'folder',
          expanded: true,
          children: [
            { id: 2, name: 'Child 1', icon: 'file', component: Item1Component },
            { id: 3, name: 'Child 2', icon: 'file', component: Item2Component }
          ]
        },
        {
          id: 4,
          name: 'Parent 2',
          icon: 'folder',
          children: [
            { id: 5, name: 'Child 3', icon: 'file', component: Item3Component },
            {
              id: 6,
              name: 'Nested Parent',
              icon: 'folder',
              children: [
                { id: 7, name: 'Nested Child', icon: 'file', component: Item1Component }
              ]
            }
          ]
        }
      ]
    },
    {
      id: 2,
      name: 'Module 2',
      icon: 'appstore',
      menuItems: Array.from({length: 20}, (_, i) => ({
        id: 8 + i,
        name: `菜单 ${i + 1}`,
        icon: 'file',
        component: Item1Component
      }))
    },
    {
      id: 3,
      name: 'Module 3',
      icon: 'appstore',
      component: Item2Component,
      menuItems: []
    }
  ];

  activeModule: Module = this.modules[0];
  menuItems: MenuItem[] = this.activeModule.menuItems;
  
  tabs: Tab[] = [];
  activeTabIndex = 0;
  isSideMenuCollapsed = false;
  maxTabCount = 30;

  constructor(private message: NzMessageService) {
    // Open first tab by default
    this.selectMenuItem(this.findFirstLeaf(this.menuItems));
  }

  private findFirstLeaf(items: MenuItem[]): MenuItem {
    for (const item of items) {
      if (!item.children) {
        return item;
      }
      const leaf = this.findFirstLeaf(item.children);
      if (leaf) {
        return leaf;
      }
    }
    return items[0];
  }

  private clearMenuSelection(items: MenuItem[]): void {
    items.forEach(item => {
      item.active = false;
      if (item.children) {
        this.clearMenuSelection(item.children);
      }
    });
  }

  private findMenuItemById(items: MenuItem[], id: number): MenuItem | null {
    for (const item of items) {
      if (item.id === id) {
        return item;
      }
      if (item.children) {
        const found = this.findMenuItemById(item.children, id);
        if (found) {
          return found;
        }
      }
    }
    return null;
  }

  private findModuleById(id: number): Module | null {
    return this.modules.find(module => module.id === id) || null;
  }

  selectModule(module: Module): void {
    // Check tab limit
    const moduleTabs = this.tabs.filter(tab => tab.moduleId === module.id);
    
    if (moduleTabs.length === 0 && this.tabs.length >= this.maxTabCount) {
      this.message.warning('标签页数量已达上限，请先关闭其他标签页');
      return;
    }
    
    this.activeModule = module;
    this.menuItems = module.menuItems;
    
    // Clear all menu selections
    this.clearMenuSelection(this.menuItems);
    
    if (moduleTabs.length > 0) {
      // Find and select the first tab's corresponding menu item
      const menuItem = this.findMenuItemById(this.menuItems, moduleTabs[0].menuItemId);
      if (menuItem) {
        menuItem.active = true;
        // Ensure the tab is active
        const tabIndex = this.tabs.findIndex(tab => tab.menuItemId === menuItem.id);
        if (tabIndex > -1) {
          this.selectTab(tabIndex);
        }
        return;
      }
    }
    
    // If no tabs, handle empty menu case
    if (this.menuItems.length === 0) {
      // Check if module already has a tab
      const moduleTab = this.tabs.find(tab => tab.moduleId === module.id);
      
      if (moduleTab) {
        // Switch to existing tab
        const tabIndex = this.tabs.indexOf(moduleTab);
        this.selectTab(tabIndex);
      } else {
        // Create default tab for module without menu items
        const newTab: Tab = {
          title: module.name,
          component: module.component,
          active: true,
          moduleId: module.id,
          menuItemId: 0
        };
        this.tabs.forEach(tab => tab.active = false);
        this.tabs.push(newTab);
        this.activeTabIndex = this.tabs.length - 1;
      }
    } else {
      // Select first leaf node
      const firstLeaf = this.findFirstLeaf(this.menuItems);
      if (firstLeaf) {
        firstLeaf.active = true;
        // Open the leaf node as a new tab
        this.selectMenuItem(firstLeaf);
      }
    }
  }

  toggleMenuItem(item: MenuItem): void {
    if (item.children) {
      item.expanded = !item.expanded;
    } else {
      this.selectMenuItem(item);
    }
  }

  selectMenuItem(item: MenuItem): void {
    if (!item.component) return;

    // Check tab limit
    if (this.tabs.length >= this.maxTabCount) {
      this.message.warning('最多只能打开4个标签页');
      return;
    }
    
    // Clear all menu selections
    this.clearMenuSelection(this.menuItems);
    item.active = true;
    
    // Check if tab already exists
    const existingTabIndex = this.tabs.findIndex(tab => tab.menuItemId === item.id);
    
    if (existingTabIndex > -1) {
      this.selectTab(existingTabIndex);
      return;
    }

    // Create new tab
    const newTab: Tab = {
      title: item.name,
      component: item.component,
      active: true,
      moduleId: this.activeModule.id,
      menuItemId: item.id
    };

    // Deactivate other tabs
    this.tabs.forEach(tab => tab.active = false);
    
    this.tabs.push(newTab);
    this.activeTabIndex = this.tabs.length - 1;
  }

  selectTab(index: number): void {
    this.tabs.forEach(tab => tab.active = false);
    this.tabs[index].active = true;
    this.activeTabIndex = index;
    
    // Update menu selection and active module
    const activeTab = this.tabs[index];
    const menuItem = this.findMenuItemById(this.menuItems, activeTab.menuItemId);
    // Find and set active module first
    const module = this.findModuleById(activeTab.moduleId);
    if (module) {
      this.activeModule = module;
      this.menuItems = module.menuItems;
      
      // Then update menu selection
      const updatedMenuItem = this.findMenuItemById(this.menuItems, activeTab.menuItemId);
      if (updatedMenuItem) {
        this.clearMenuSelection(this.menuItems);
        updatedMenuItem.active = true;
      }
    }
  }

  closeTab(index: number): void {
    // Prevent closing the last tab
    if (this.tabs.length <= 1) {
      return;
    }
    
    this.tabs.splice(index, 1);
    
    if (this.tabs.length > 0) {
      const newIndex = Math.min(index, this.tabs.length - 1);
      this.selectTab(newIndex);
    }
  }

  toggleSideMenu(): void {
    this.isSideMenuCollapsed = !this.isSideMenuCollapsed;
  }

  logout(): void {
    // TODO: Implement logout logic
    console.log('User logged out');
  }
}
